function Auth() {
    this.mask = $('.mask-wrapper');
    this.scroll_wrapper = $('.scroll-wrapper');
    this.signin_btn = $('#signin-btn');
    this.signup_btn = $('#signup-btn');
    this.ctl = $('.window-control');
    this.header = $('#header');
    this.headerNav = $('.nav');
}

/**
 * 登录按钮点击事件
 */
Auth.prototype.listenSigninBtnEvent = function () {
    var self = this;
    this.signin_btn.click(function () {
        self.showEvent();
        self.scroll_wrapper.animate({'left': '0'});
    })
};

/**
 * 注册按钮点击事件
 */
Auth.prototype.listenSignupBtnEvent = function () {
    var self = this;
    this.signup_btn.click(function () {
        self.showEvent();
        self.scroll_wrapper.animate({'left': '-400px'});
    })
};

/**
 * 隐藏模态对话框
 */
Auth.prototype.hideEvent = function () {
    document.body.style.overflow = 'auto';
    this.mask.hide();
};

/**
 * 显示模态对话框
 */
Auth.prototype.showEvent = function () {
    document.body.style.overflow = 'hidden';
    this.mask.show();
};

/**
 * 点击关闭模态对话框
 */
Auth.prototype.listenCloseBtnEvent = function () {
    var self = this;
    $('.close-btn').click(function () {
        self.hideEvent();
        $('input[name="password"]').val('');
    })
};

/**
 * 点击立即登录和立即注册滑动模态对话框
 */
Auth.prototype.listenSwitchBtnEvent = function () {
    var self = this;
    $('.switch').click(function () {
        var current_left = self.scroll_wrapper.css('left');
        current_left = parseInt(current_left);
        if (current_left >= 0) {
            self.scroll_wrapper.animate({left: '-400px'})
        } else {
            self.scroll_wrapper.animate({left: '0'})
        }
    })
};

/**
 * 点击立即登录发送ajax请求
 */
Auth.prototype.listenSigninAjaxEvent = function () {
    var self = this;
    var signin_group = this.scroll_wrapper.find('.signin-group');
    var emailInput = signin_group.find("input[name='email']");
    var passwordInput = signin_group.find("input[name='password']");
    var rememberInput = signin_group.find("input[name='remember']");
    var btn = signin_group.find(".submit-btn");
    btn.click(function () {
        var email = emailInput.val();
        var password = passwordInput.val();
        var remember = rememberInput.prop('checked');
        myajax.post({
            'url': '/account/login/',
            'data': {
                'email': email,
                'password': password,
                'remember': remember ? 1 : 0
            },
            'success': function (result) {
                if (result['code'] === 200) {
                    self.hideEvent();
                    window.location.href = window.location.href;
                    window.location.reload();
                }
            }
        });
    })
};

/**
 * 点击立即注册发送ajax请求
 */
Auth.prototype.listenSignupAjaxEvent = function () {
    var self = this;
    var signup_group = this.scroll_wrapper.find('.signup-group');
    var emailInput = signup_group.find("input[name='email']");
    var passwordInput = signup_group.find("input[name='password']");
    var passwordRepeatInput = signup_group.find("input[name='password_repeat']");
    var usernameInput = signup_group.find('input[name="username"]');
    var imgCaptchaInput = signup_group.find('input[name="img_captcha"]');
    var emailCaptchaInput = signup_group.find('input[name="email_captcha"]');
    var btn = signup_group.find(".submit-btn");
    btn.click(function () {
        var email = emailInput.val();
        var username = usernameInput.val();
        var password = passwordInput.val();
        var passwordRepeat = passwordRepeatInput.val();
        var imgCaptcha = imgCaptchaInput.val();
        var emailCaptcha = emailCaptchaInput.val();
        myajax.post({
            'url': '/account/register/',
            'data': {
                'email': email,
                'username': username,
                'password': password,
                'password_repeat': passwordRepeat,
                'img_captcha': imgCaptcha,
                'email_captcha': emailCaptcha
            },
            'success': function (result) {
                if (result['code'] === 200) {
                    window.location.href = window.location.href;
                    window.location.reload();
                }
            }
        });
    })
};

/**
 * 点击图形验证码重新请求图形验证码
 */
Auth.prototype.listenImageCaptchaEvent = function () {
    var img_captcha = this.scroll_wrapper.find('.image');
    img_captcha.click(function () {
        img_captcha.attr('src', '/account/img_captcha/' + '?random=' + (new Date()).getTime());
    })
};

/**
 * 发送邮件成功等待事件
 * @constructor
 */
Auth.prototype.EmailSuccessEvent = function () {
    var self = this;
    var btn = this.scroll_wrapper.find('.email-captcha-btn');
    btn.addClass('disabled');
    btn.unbind('click');
    btn.css({'cursor': 'default'});
    btn.text('请等待60秒');
    var count = 59;
    var timer = setInterval(function () {
        btn.text('请等待' + count + '秒');
        count--;
        if (count <= 0) {
            clearInterval(timer);
            btn.removeClass('disabled');
            btn.text('发送验证码');
            btn.css({'cursor': 'pointer'});
            self.listenEmailSend();
        }
    }, 1000);
};

/**
 * 点击发送邮箱验证码
 */
Auth.prototype.listenEmailSend = function () {
    var self = this;
    var btn = this.scroll_wrapper.find('.email-captcha-btn');
    var signup = this.scroll_wrapper.find('.signup-group');
    var emailInput = signup.find('input[name="email"]');

    btn.click(function () {
        var email = emailInput.val();
        if (email == '') {
            window.messageBox.showInfo('请输入邮箱！');
            return;
        }
        myajax.post({
            'url': '/account/email_captcha/',
            'data': {
                'email': email
            },
            'success': function (result) {
                if (result['code'] === 200) {
                    window.messageBox.showSuccess('验证码发送成功！');
                    self.EmailSuccessEvent();
                } else {
                    window.messageBox.showInfo(result['message']);
                }
            }
        })
    })
};

/**
 * 滚动到一定距离显示windowControl按钮
 * @constructor
 */
Auth.prototype.HandelHeader = function () {
    var self = this;
    window.onscroll = function () {
        var t = document.documentElement.scrollTop || document.body.scrollTop;
        if (t >= 76) {
            self.header.css({'opacity': 0.5});
            self.ctl.show();
        } else {
            self.header.css({'opacity': 1});
            self.ctl.hide();
        }
    }
};

/**
 * 控制立即到头尾的点击
 * @constructor
 */
Auth.prototype.PageSilder = function () {
    var toTop = this.ctl.find('li').eq(0);
    var toBottom = this.ctl.find('li').eq(1);
    toTop.on("click", function () {
        $('body,html').animate({scrollTop: 0}, 500);
        return false;
    });
    toBottom.on("click", function () {
        var bottom = $(document).height();
        $('body,html').animate({scrollTop: bottom}, 500);
        return false;
    });
};

/**
 * 根据当前的url来改变头部的蓝色下标的位置
 */
Auth.prototype.checkUrl = function () {
    var strUrl = window.location.href;
    var arrUrl = strUrl.split("/");
	if (arrUrl.length === 4){
		this.headerNav.children('li').eq(0).addClass('active').siblings().removeClass('active');
	}else{
		var str = arrUrl[arrUrl.length-2];
		this.headerNav.children('.'+str).addClass('active').siblings().removeClass('active');
	}
};

/**
 * 入口
 */
Auth.prototype.run = function () {
    this.listenSigninBtnEvent();
    this.listenSignupBtnEvent();
    this.listenCloseBtnEvent();
    this.listenSwitchBtnEvent();
    this.listenSigninAjaxEvent();
    this.listenSignupAjaxEvent();
    this.listenImageCaptchaEvent();
    this.listenEmailSend();
    this.HandelHeader();
    this.PageSilder();
    this.checkUrl();
};

$(function () {
    var auth = new Auth();
    auth.run();
});

$(function(){
    if (!template)
        return;
    //在arttemplate中定义的过滤器
    template.defaults.imports.timeSince = function(dateVal){
        var date = new Date(dateVal);
        var datets = date.getTime();
        var nowts = (new Date()).getTime();
        var timestamp = (nowts - datets) / 1000;
        if (timestamp < 60) {
            return '刚刚';
        }else if(timestamp >= 60 && timestamp < 60 * 60){
            var minutes = parseInt(timestamp / 60);
            return minutes + '分钟前';
        }else if(timestamp >= 60 * 60 && timestamp < 60 * 60 * 12){
            var hours = parseInt(timestamp / (60 * 60));
            return hours + '小时前';
        }else if(timestamp >= 60 * 60 * 12 && timestamp < 60 * 60 * 12 * 30){
            var days = parseInt(timestamp / (60 * 60 * 12));
            return days + '天前';
        }else if(timestamp >= 60 * 60 * 12 * 30 && timestamp < 60 * 60 * 12 * 30 * 12){
            var months = parseInt(timestamp / (60 * 60 * 12 * 30));
            return months + '月前';
        }else if(timestamp >= 60 * 60 * 12 * 30 * 12){
            var year = date.getFullYear();
            var month = date.getMonth();
            var day = date.getDay();
            var hour = date.getHours();
            var minute = date.getMinutes();
            return year + '/' + month + '/' + day + ' ' + hour + ':' + minute;
        }
    }
});
